package cn.sumpu.app.guoguojie.web.mvc.member;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.sumpu.app.guoguojie.biz.IdentifierBiz;
import cn.sumpu.app.guoguojie.biz.ImageBiz;
import cn.sumpu.app.guoguojie.biz.WeiboBiz;
import cn.sumpu.app.guoguojie.constant.OutAccountType;
import cn.sumpu.app.guoguojie.domain.DoingSync;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;
import cn.sumpu.app.guoguojie.util.ImageWeb;
import cn.sumpu.app.guoguojie.util.PageModel;

/**
 * 
 * @author grieous
 * @version $Id: WeiboController.java, v 0.1 2012-9-9 上午10:59:17 grieous Exp $
 */
@Controller
public class WeiboController {
    private final static Logger logger = LoggerFactory.getLogger(WeiboController.class);
    @Autowired
    private WeiboBiz            weiboBiz;
    @Autowired
    private IdentifierBiz       idBiz;
    @Autowired
    private ImageBiz            imageBiz;

    /**
     * 分享内容到新浪微博和腾讯微博
     * @author grieous
     * 
     * @param shareType 01-新浪微博 03-腾讯微博
     * @param text  分享的文本内容
     * @param picurl 分享的图片链接(网络图)
     * @param shareurl  分享的链接
     * @return
     */
    @RequestMapping(value = "/weibo/share.htm")
    public String easyRegister(HttpServletResponse response, String shareType, String text, String picurl, String shareurl) {
        try {
            if (!Common.empty(text) && !Common.empty(picurl) && !Common.empty(shareurl)) {
                
                if (shareType.equals(OutAccountType.SINA_WEIBO.getValue())) {
                    String toUrl = weiboBiz.shareSina(text, shareurl, picurl, "http://www.guoguojie.com/");
                    response.sendRedirect(toUrl);
                } else if (shareType.equals(OutAccountType.TENCENT_WEIBO.getValue())) {
                    String toUrl = weiboBiz.shareTencent(text, shareurl, picurl, "http://www.guoguojie.com/");
                    response.sendRedirect(toUrl);
                }
            }

        } catch (Exception e) {
            logger.error("[/weibo/share.htm] fail", e);
        }
        return null;
    }

    @RequestMapping(value = "/misc/weibo/weibo.htm")
    public String weibo(HttpServletRequest request) {
        return "misc/weibo/weibo";
    }

    @RequestMapping(value = "/misc/weibo/addweibo.htm")
    public String addWeibo(HttpServletRequest request) {
        try {
            String id = idBiz.generateId("doing_sync");
            request.setAttribute("id", id);
            request.setAttribute("saveType", "add");
        } catch (AppBusinessException e) {
            logger.error("[/misc/weibo/addweibo.htm] fail", e);
        }

        return "misc/weibo/saveWeibo";
    }

    @RequestMapping(value = "/misc/weibo/weibogrid.htm")
    public String weiboGrid(Integer page, Integer pagesize, String status, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            PageModel pageModel = weiboBiz.getDoingSync(page, pagesize, status);
            pw = response.getWriter();
            pw.print(JSONObject.fromObject(pageModel));
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/weibo/weibogrid.htm] fail", e);
            }
        }
        return null;
    }

    @RequestMapping(value = "/misc/weibo/editdoingsync.htm")
    public String editLuck(HttpServletRequest request, String id) {
        try {
            DoingSync doingSync = weiboBiz.getDoingSyncById(id);
            request.setAttribute("doingSync", doingSync);
            request.setAttribute("saveType", "edit");
            request.setAttribute("id", id);
        } catch (AppBusinessException e) {
            logger.error("/misc/weibo/editdoingsync.htm", e);
        }
        return "misc/weibo/saveWeibo";
    }

    @RequestMapping(value = "/misc/weibo/deletedoingsync.htm")
    public String deleteSyncDoing(String doingSyncId, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        try {
            PrintWriter pw = response.getWriter();
            DoingSync doingSync=weiboBiz.getDoingSyncById(doingSyncId);
            if (!Common.empty(doingSync)) {
                String url = doingSync.getPictureUrl();
                if (!Common.empty(url)) {
                    int index = url.indexOf("pic");
                    int lastIndex = url.lastIndexOf("pic");
                    String imageServer = "";
                    String imageFile = "";
                    if (index > 0 && lastIndex > 0) {
                        imageServer = url.substring(0, index);
                        imageFile = url.substring(lastIndex);
                        imageBiz.requestDeleteImage(imageServer + "deleteImage.htm", imageFile);
                    }

                }
            }
            weiboBiz.deleteDoingSync(doingSyncId);
            pw.print("success");
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/cms/postsyncdoing.htm] fail", e);
            }
        }
        return null;
    }

    // 后台发送一条定时微博
    @RequestMapping(value = "/misc/cms/savedoingsync.htm")
    public String postSyncDoing(DoingSync doingSync, String saveType, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html; charset=UTF-8");
        try {
            doingSync.setPostIp(Common.getIp(request));
            PrintWriter pw = response.getWriter();
            weiboBiz.saveDoingSync(doingSync, saveType);
            pw.print("success");
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error("[/misc/cms/postsyncdoing.htm] fail", e);
            }
        }
        return null;
    }

    //上传定时微博图片
    @RequestMapping(value = "/misc/weibo/upload.htm")
    public String uploadLogo(HttpServletRequest request, HttpServletResponse response, String identifier) {
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter pw = null;
        try {
            String fileType = "weibo";
            String fileName = identifier;
            request.setAttribute("fileType", fileType);
            request.setAttribute("fileName", fileName);
            ImageWeb imageWeb = imageBiz.uploadOneImg(request);
            pw = response.getWriter();
            pw.println(JSONObject.fromObject(imageWeb).toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("[/misc/weibo/upload.htm] fail", e);
        }
        return null;
    }
}
